﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 购物车
    /// </summary>
    [Route("account/shop/cart")]
    [ApiController]
    public class ShopCartController : ControllerBase
    {
        private readonly IShopCartService _shopCartService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public ShopCartController(IShopCartService shopCartService, IUserService userService, IMapper mapper)
        {
            _shopCartService = shopCartService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 普通账户调用接口========================
        /// <summary>
        /// 获取购物车列表
        /// 示例：/account/shop/cart/list
        /// </summary>
        [HttpGet("list")]
        [Authorize]
        public async Task<IActionResult> GetList([FromQuery] BaseParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopCartDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopCartDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据库列表
            var resultFrom = await _shopCartService.GetListAsync(
                x => (searchParam.MerchantId <= 0 || x.MerchantId == searchParam.MerchantId)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.Title != null && x.Title.Contains(searchParam.Keyword))),
                WriteRoRead.Write);

            //根据字段进行塑形
            var resultDto = resultFrom.AsEnumerable().ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/account/shop/cart
        /// </summary>
        [HttpPost]
        [Authorize]
        public async Task<IActionResult> Add([FromBody] ShopCartEditDto modelDto)
        {
            //保存数据
            var result = await _shopCartService.AddAsync(modelDto);
            if (!result)
            {
                return BadRequest(ResponseMessage.Error("购物车商品更新失败"));
            }
            return NoContent();
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/account/shop/cart/1
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        public async Task<IActionResult> Update([FromRoute] long id, [FromQuery] int quantity)
        {
            //保存数据
            var result = await _shopCartService.UpdateAsync(id, quantity);
            if (!result)
            {
                return BadRequest(ResponseMessage.Error("购物车商品更新失败"));
            }
            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/account/shop/cart/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        public async Task<IActionResult> Delete([FromRoute] long id)
        {
            if (!await _shopCartService.ExistsAsync<ShopCart>(x => x.Id == id))
            {
                return NotFound(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _shopCartService.DeleteAsync(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/account/shop/cart?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _shopCartService.DeleteAsync(x => arrIds.Contains(x.Id));

            return NoContent();
        }

        /// <summary>
        /// 获取购买商品列表
        /// 示例：/account/shop/cart/buy
        /// </summary>
        [HttpGet("buy")]
        [Authorize]
        public async Task<IActionResult> GetBuyList([FromQuery] string jsonData)
        {
            //检查参数是否正确
            if (jsonData == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //转换成对象
            var listDto = JsonHelper.ToObject<List<ShopCartEditDto>>(jsonData);
            if(listDto == null)
            {
                return BadRequest(ResponseMessage.Error("无法获取商品列表，请检查重试"));
            }
            //获取数据库列表
            var result = await _shopCartService.GetBuyListAsync(listDto);
            //返回成功200
            return Ok(result);
        }
        #endregion

        #region 前台调用接口============================
        /// <summary>
        /// 获取总记录数量
        /// 示例：/client/shop/cart/count
        /// </summary>
        [HttpGet("/client/shop/cart/count")]
        public async Task<IActionResult> GetCount([FromQuery] BaseParameter searchParam)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return Ok(0);
            }
            var result = await _shopCartService.QueryCountAsync(x => x.UserId==userId);
            //返回成功200
            return Ok(result);
        }
        #endregion

    }
}
